<template>
  <div>
    <!-- 查询，增加 -->
    <el-card>
      <el-form :inline="true" :model="params">
        <el-form-item label="编码">
          <el-input v-model="params.skuId" placeholder="按编码查找"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getList(1)" icon="el-icon-search"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button style="margin-left:450px" type="success" @click="add" icon="el-icon-plus"
            >增加</el-button
          >
          <el-button type="danger" @click="removeMore" icon="el-icon-delete"
            >批量删除</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 表格 -->
    <el-card>
      <el-table :data="rows" stripe style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="skuId" label="SKU编码"> </el-table-column>
        <el-table-column prop="salePrice" label="售价"> </el-table-column>
        <el-table-column prop="originalPrice" label="原价"> </el-table-column>
        <el-table-column prop="productName" label="商品名称"></el-table-column>
          <el-table-column prop="imgs" label="图片">
            <template slot-scope="scope">
              <img style="width:40px;height:40px" v-if="scope.row.imgs" :src="scope.row.imgs" />
            </template>
          </el-table-column>
        <el-table-column prop="props" label="属性"></el-table-column>
        <el-table-column prop="skuSpecification" label="直连供应商"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
            style="margin-bottom:10px;"
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="edit(scope.row)"
              >编辑</el-button
            >
            <el-popconfirm
              title="确定删除此数据吗？"
              @confirm="remove(scope.row)"
            >
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-refresh-right"
                slot="reference"
                >删除</el-button
              >
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          @size-change="SizeChange"
          @current-change="getList"
          :current-page="params.pageNum"
          :page-sizes="[5, 10, 20]"
          :page-size="params.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
    <el-dialog :skuId="form._id ? '修改' : '新增'" :visible.sync="dialogFormVisible" width="400px">
      <el-form :model="form" ref="form" :rules="rules" label-width="100px">
        <el-form-item label="SKU编码" prop="skuId">
          <el-input type="text" v-model="form.skuId"></el-input>
        </el-form-item>
        <el-form-item label="售价" prop="salePrice">
          <el-input type="text" v-model="form.salePrice"></el-input>
        </el-form-item>
        <el-form-item label="原价" prop="originalPrice">
          <el-input type="text" v-model="form.originalPrice"></el-input>
        </el-form-item>
        <el-form-item label="商品名称" prop="productName">
          <el-input type="text" v-model="form.productName"></el-input>
        </el-form-item>
        <el-form-item label="图片" prop="imgs">
          <div @click="openFile" style="overflow:hidden;width:100px;height:100px;font-size:32px;border:1px dashed #ccc;text-align:center;line-height:100px">
            <img style="max-width:100%;max-height:100%" v-if="form.imgs" :src="form.imgs" />
            <span v-else>+</span>
          </div>
          <input ref="file" style="display:none;" multiple accept="image/*" type="file" @change="changeFile"/>
        </el-form-item>
        <el-form-item label="属性" prop="props">
            <el-input type="text" v-model="form.props"></el-input>
        </el-form-item>
        <el-form-item label="直连供应商" prop="skuSpecification">
            <el-input type="textarea" v-model="form.skuSpecification"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import api from '@/api'
export default {
  components: {},
  data() {
    return {
      ///查询参数
      params: {
        skuId: '',
        pageNum: 1,
        pageSize: 5,
      },
      rows: [],
      total: 0,
      dialogFormVisible: false,
      form: {
        _id: 0,
        skuId:'',
        salePrice:'',
        originalPrice:'',
        productName:'',
        imgs: '',
        props:'',
        skuSpecification:''
      },
      rules: {
        imgs: [{ required: true, message: "图片不能为空", trugger: "blur" }],
      },
            selecteds: [
      ]
    };
  },
  methods: {
    //获取列表
    getList(pageNum) {
      if (pageNum) this.params.pageNum = pageNum;
      this.$http({
        url: '/admin/singleproduct',
        params: this.params,
      }).then((res) => {
        this.total = res.total;
        this.rows = res.rows;
      });
    },

    //修改pageSize
    SizeChange(pageSize) {
      this.params.pageSize = pageSize;
      this.getList(1);
    },
    add() {
      //初始化
      this.form = {
        _id:0,
        skuId:'',
        salePrice:'',
        originalPrice:'',
        productName:'',
        imgs: '',
        props:'',
        skuSpecification:''
      }
      this.dialogFormVisible = true;
    },

    //修改数据
    edit(row) {
      this.form = row;
      this.dialogFormVisible = true;
    },

    //删除数据
    remove(row) {
      this.$http({
        url: '/admin/singleproduct',
        method: 'DELETE',
        params: {indexId:row._id},
      }).then(res => {
        if (!res.errorMsg) {
          this.getList(1);
        }
      });
    },
    handleSelectionChange(rows){
      //存储选中数据
      this.selecteds = rows
    },

    //批量删除
    removeMore(){
      //获取被选中的数据
      let checkedRowsPrmose = []
      let success = [],fail = []
      for(let i = 0 ; i < this.selecteds.length; i ++){
        checkedRowsPrmose.push(
          new Promise(resovle => {
            let row = this.selecteds[i]
            this.$http({
              url:'/admin/singleproduct',
              method:'DELETE',
              params:{indexId:row._id}
            }).then(res => {
              if(!res.errorMsg){
                success.push(row._id)
              }else{
                fail.push(row._id)
              }
              resovle()
            })
          })
        )
      }
       this.$confirm('此操作将删除选中的数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //删除数据
        Promise.all(checkedRowsPrmose).then(() => {
          this.$message({
            message: `批量删除完成，成功删除${success.length}条数据，删除失败${fail.length}条数据`,
            duration:3000
          })
          this.getList(1)
        })
      })
    },
    //新增数据
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.form.indexId = this.form._id
          this.$http({
            url: '/admin/singleproduct',
            method: this.form.indexId ? 'PUT' : 'POST',//通过indexId判断是新增还是修改
            data: this.form,
          }).then((res) => {
            if (!res.errorMsg) {
              this.dialogFormVisible = false;
              this.getList(this.form.indexId ? undefined : 1);
            }
          });
        }
      });
    },
    openFile(){
      let fileElement = this.$refs.file
      fileElement.click()
    },
    changeFile(e){
      let files = e.target.files
      let formData = new FormData()
      formData.append('file',files[0])
      this.$http({
        url:'/upload',
        method:'POST',
        data:formData
      }).then(res => {
        if(res.path) this.form.imgs = api.baseURL + '/' + res.path.slice(0,7) + '/' + res.path.slice(8)
      })
    },
  },
  created() {
    this.getList();
    // this.$http("/admin/index/banners").then((banners) => {
    //   console.log(banners);
    // });
  },
  mouted() {},
};
</script>

<style scoped>
.el-card {
  margin-bottom: 20px;
}
.block {
  margin-top: 20px;
}
</style>
